<!doctype html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport"
		  content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
	<title>单词秒刷</title>
	<!-- <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>-->
	<!-- <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.3.1/css/bootstrap.min.css"> -->
	<!-- 其他头部内容 -->
	<link rel="stylesheet" href="css/bootstrap.min.css">
	<script src="./js/jquery-3.6.0.min.js"></script>
	<script src="./js/bootstrap.bundle.min.js"></script>
	<!-- <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> -->
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
	<link rel="stylesheet" href="css/all.min.css">
	<link rel="stylesheet" href="./css/pageStyle.css">
</head>
<body>
<!-- 顶部显示区域 -->
<div id="topdisplay">
	<p style="margin-left: 20px; ">单词记忆系统</p>
	<button id="setweb" style="background-color: black;color: white; border: 0px;margin-left: 5%;width: 50px;"
			class="btn"></button>
	<p style="margin-left: 60%;">当前登录用户:
		<select id="loginUserImport" class="custom-select"
				style="width:150px;color: white;background-color: black;caret-color: white;"></select>
	</p>
</div>

<!-- 左侧功能切换区域 -->
<div id="leftnav">
	<ul>
		<li id="memoryAction" class="leftli"><i class="fas fa-book"></i>
			<p style="display: initial;">单词记忆</p>
		</li>
		<li id="wordDataAction" class="leftli" style="margin-top: 2px;"><i class="fas fa-chart-bar"></i>
			<p style="display: initial;">单词数据</p>
		</li>
		<li id="lexiconData" class="leftli" style="margin-top: 2px;"><i class="fas fa-chart-bar"></i>
			<p style="display: initial;">词本数据</p>
		</li>
		<li id="learn_logData" class="leftli" style="margin-top: 2px;"><i class="fas fa-chart-bar"></i>
			<p style="display: initial;">学习记录</p>
		</li>
	</ul>
</div>

<!-- 中间功能显示区域 -->
<div id="displayBox">

	<!-- 单词记忆功能区域 -->
	<div id="memoryDIV" class="displaydiv">
		<ul id="nav" class="list-group list-group-horizontal" style="margin-top: 30px;">
			<li id="Quick_brush" class="list-group-item list-group-item-action text-center"
				style=" border-radius: 8px;">速刷</li>
			<li id="ChineseToEnglish" style="margin-left: 4px; border-radius: 8px;"
				class="list-group-item list-group-item-action text-center">汉译英</li>
			<li id="addWord" style="margin-left: 4px; border-radius: 8px;"
				class="list-group-item list-group-item-action text-center">添加单词</li>
		</ul>
		<div>
			<div id="English">
				<p id="nextEnglish" class="text-center" style="font-size: 20px;">English</p>
				<textarea class="form-control" id="ttsBaiduText" placeholder="请输入英文单词"></textarea>
			</div>
			<div id="Chinese">
				<p id="nextChinese" class="text-center" style="font-size: 20px;">Chinese</p>
				<textarea class="form-control" id="ChineseText" placeholder="请输入中文翻译"></textarea>
			</div>
		</div>
		<!-- 按钮组 -->
		<div class="buttons-container">
			<button id="ttsBaiduPlay" class="btn btn-info">朗读</button>
			<button id="select" class="btn btn-info">查看</button>
			<button id="forget" class="btn btn-info">遗忘</button>
			<button id="addWordTOdb" class="btn btn-info">添加</button>
			<select class="custom-select text-center" style="width:20%;display: inline-block;
					" name="词本" id="momoryLexicon">
				<option value="" disabled selected>请选择词本</option>
			</select>
		</div>
		<div id="wordLoginfo">
			<form id="logform" action="">
				<table class="table table-striped table-bordered text-center">
					<thead>
					<tr>
						<th>单词</th>
						<th>释义</th>
						<th>正确次数</th>
						<th>错误次数</th>
					</tr>
					</thead>
					<tbody id="logInfoTable" class="table table-striped table-bordered text-center">
					<!-- 表格内容 -->
					</tbody>
				</table>
			</form>
		</div>


		<!-- 单词速刷 -->
		<div id="Quick_brushModal" style="" class="modal fade" tabindex="-1" role="dialog">
			<div class="modal-dialog" role="document">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title">单词速刷</h5>
						<button type="button" class="close" data-dismiss="modal" aria-label="Close"
								onclick="closeEdit(this)">
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div class="modal-body">
						<!-- 编辑表单内容 -->
						<div style="width: 100%; height: 500px;border: 1px;">
							<div id="quick_wordDIV">
								<p class="text-center" id="quick_wordDIV_text">word</p>
								<input style="margin-left: 40%;width: 20%;" class=" btn btn-primary" type="submit" value="遗忘">
							</div>
							<!-- 速刷选择区 -->
							<div id="quick_chooseDIV">
								<input class="btn btn-primary text-center" type="submit" value="Submit">
								<input class="btn btn-primary" type="submit" value="Submit">
								<input class="btn btn-primary" type="submit" value="Submit">
								<input class="btn btn-primary" type="submit" value="Submit">
							</div>
						</div>

					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-dismiss="modal"
								onclick="closeEdit(this)">关闭</button>
						<!-- <button type="button" class="btn btn-primary" onclick="saveWord()">保存</button> -->
					</div>
				</div>
			</div>
		</div>
	</div>

	<!-- 单词数据显示功能区 -->
	<div id="wordDataDIV" class="displaydiv" style="width: 100%;">
		<div class="container">
			<h3>单词列表</h3>
			<div class="row" style="margin-bottom: 10px; ">
				<div class="col-md-6" style="width: 100%;">
					<input id="searchInput" style="width:100%;display: inline-block;" type="text"
						   class="form-control text-center" placeholder="模糊查询">

				</div>
				<select class="custom-select text-center" style="width:20%;display: inline-block;" name="词本"
						id="lexicon">
					<option value="" disabled selected>请选择词本</option>
				</select>
			</div>
			<table id="wordDataTable" class="table table-striped table-bordered  text-center">
				<thead>
				<tr>
					<th>单词</th>
					<th>释义</th>
					<th>正确</th>
					<th>错误</th>
					<th>强度</th>
					<th>间隔</th>
					<th>下一次时间</th>
					<th>操作</th>
				</tr>
				</thead>
				<tbody>
				<!-- 动态生成的数据行将插入到这里 -->
				</tbody>
			</table>
			<div id="pagination" class="text-center">
				<!-- 分页和页码跳转将插入到这里 -->

			</div>

			<span id="pageshowSum"></span>


		</div>
		<!-- //编辑表单 -->
		<div id="editModal" class="modal fade" tabindex="-1" role="dialog">
			<div class="modal-dialog" role="document">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title">编辑单词</h5>
						<button type="button" class="close" data-dismiss="modal" aria-label="Close"
								onclick="closeEdit()">
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div class="modal-body">
						<!-- 编辑表单内容 -->
						<form id="editForm">
							<div class="form-group">
								<label for="editWordInput">单词</label>
								<input type="text" class="form-control" id="editWordInput" name="editWord"
									   placeholder="请输入单词">
							</div>
							<div class="form-group">
								<label for="editMeaningInput">释义</label>
								<input type="text" class="form-control" id="editMeaningInput" name="editMeaning"
									   placeholder="请输入释义">
							</div>
							<!-- 其他编辑字段 -->
						</form>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-dismiss="modal"
								onclick="closeEdit()">关闭</button>
						<button type="button" class="btn btn-primary" onclick="saveWord()">保存</button>
					</div>
				</div>
			</div>
		</div>

		<!-- 提醒框 -->

	</div>

	<!-- 词本数据功能组件 -->
	<div id="lexiconDIV" style="overflow: auto;" class="displaydiv">
		<div class="container">
			<h3>词本数据</h3>
			<table id="lexiconTable" class="table table-striped table-bordered  text-center">
				<thead>
				<tr>
					<th>ID</th>
					<th>词本作者</th>
					<th>词本名称</th>
					<th>单词数量</th>
					<th>词本状态</th>
					<th>操作</th>
				</tr>
				</thead>
				<tbody>
				<!-- 动态生成的数据行将插入到这里 -->
				</tbody>
			</table>
		</div>

	</div>


	<!-- 学习记录功能模块 -->
	<div id="learn_logDIV" style="overflow: auto;" class="displaydiv">
		<div class="container">
			<h3>学习记录</h3>
			<table id="learn_logTable" class="table table-striped table-bordered  text-center">
				<thead>
				<tr>
					<th>日期</th>
					<th>学习总量</th>
					<th>规划复习</th>
					<th>正确</th>
					<th>错误</th>
					<th>添加</th>
					<th>总学习次数</th>
				</tr>
				</thead>
				<tbody>
				<!-- 动态生成的数据行将插入到这里 -->
				</tbody>
			</table>
		</div>

	</div>

</div>


<script type="text/javascript">
	var i = 0;
	// 获取数据
	let userData = JSON.parse(sessionStorage.getItem('userKey'))
	if (userData === null || userData === undefined)
		window.location.href = "login.html";
	const token = userData.token
	console.log(userData)
	$("#wordDataDIV").hide()
	$("#learn_logDIV").hide()
	//单词记忆功能切换点击事件
	$("#memoryAction").click(function() {
		$(".displaydiv").hide()
		$("#memoryDIV").show()
	})
	// 单词数据功能切换点击事件
	$("#wordDataAction").click(function() {
		$(".displaydiv").hide()
		$("#wordDataDIV").show()
		//获取词本分类
		getLexiconData()
		//获取总页码
		getPageNumber()

	})

	//词本数据功能切换点击事件
	$("#lexiconData").click(function() {
		$(".displaydiv").hide()
		$("#lexiconDIV").show()
		getLexicons()
	})

	//学习记录功能切换点击事件
	$("#learn_logData").click(function() {
		$(".displaydiv").hide()
		$("#learn_logDIV").show()
		getLearnlog()
	})

	//获取学习记录
	function getLearnlog() {
		$.ajax({
			url: "http://localhost:8080/learnLog/" + userData.userAccount,
			type: "GET",
			headers: {
				'Content-Type': 'application/json',
				"token": token
			},
			data: JSON.stringify(), // 将请求数据转换为JSON字符串
			success: function(response) {
				// 清空表格内容
				$("#learn_logDIV tbody").empty();
				// 根据接口返回的数据生成表格行
				var selected = "selected"
				for (var i = 0; i < response.data.length; i++) {
					var learnData = response.data[i];
					var row = "<tr>" +
							"<td>" + learnData.date + "</td>" +
							"<td>" + learnData.learn_sum + "</td>" +
							"<td>" + learnData.review + "</td>" +
							"<td>" + learnData.right + "</td>" +
							"<td>" + learnData.wrong + "</td>" +
							"<td>" + learnData.insert_word + "</td>" +
							"<td>" + learnData.learn_sums + "</td>" +
							"</tr>";
					$("#learn_logTable tbody").append(row);
				}
			},
			error: function(response) {
				if (response.status == 401) {
					//token验证不通过
					window.location.href = "login.html";
				}
			}

		});
	}
	//获取词本数据
	function getLexicons() {
		$.ajax({
			url: "http://localhost:8080/lexicons",
			type: "POST",
			headers: {
				'Content-Type': 'application/json',
				"token": token
			},
			data: JSON.stringify(), // 将请求数据转换为JSON字符串
			success: function(response) {
				// 清空表格内容
				$("#lexiconDIV tbody").empty();
				// 根据接口返回的数据生成表格行
				var selected = "selected"
				for (var i = 0; i < response.data.length; i++) {
					var lexiconData = response.data[i];
					var td = ""
					var handle = ""

					if (userData.userAccount == lexiconData.account) {
						handle = "<button class='btn btn-primary' onclick='lexiconDelete(" + lexiconData.id +
								")'>删除</button>"
						if (lexiconData.show == 1) {
							td = "<select class='custom-select text-center'><option value='" + lexiconData
											.id + "' selected>公开</option><option value='" + lexiconData.id +
									"'>私有</option></select > "
						} else {
							td = "<select class='custom-select text-center'><option value='" + lexiconData
											.id + "' >公开</option><option value='" + lexiconData.id +
									"'selected>私有</option></select > "
						}
					} else {
						handle = handle = "<button class='btn btn-primary' onclick='insertLexicon(" +
								lexiconData.id + ")'>引入</button>"
						td = "<select disabled class='custom-select text-center'><option value='" +
								lexiconData.id + "'disabled selected>公开</option>"
					}
					// console.log(pagewordData)
					var row = "<tr>" +
							"<td>" + lexiconData.id + "</td>" +
							"<td>" + lexiconData.account + "</td>" +
							"<td>" + lexiconData.name + "</td>" +
							"<td>" + lexiconData.word_Number + "</td>" +
							"<td>" + td + "</td>" +
							"<td>" + handle + "</td>" +
							"</tr>";
					$("#lexiconTable tbody").append(row);
				}

				updatePagination(pageSize, currentPage)
			},
			error: function(response) {
				if (response.status == 401) {
					//token验证不通过
					window.location.href = "login.html";
				}
			}

		});
	}

	function insertLexicon(id){
		prompt("账户权限不足，无法使用此功能")
	}

	//删除词本
	function lexiconDelete(id) {
		$.ajax({
			url: "http://localhost:8080/lexicons/" + id,
			type: "Delete",
			headers: {
				'Content-Type': 'application/json',
				"token": token
			},
			data: JSON.stringify(), // 将请求数据转换为JSON字符串
			success: function(response) {
				getLexicons()
				prompt(response.data.msg)
			},
			error: function(response) {
				if (response.status == 401) {
					//token验证不通过
					window.location.href = "login.html";
				}
			}
		});
	}
	//获取分页页码
	function getPageNumber() {
		$.ajax({
			url: "http://localhost:8080/word",
			type: "GET",
			headers: {
				'Content-Type': 'application/json',
				"token": token
			},
			data: JSON.stringify(), // 将请求数据转换为JSON字符串
			success: function(response) {
				pageSize = response.data.length / 7
			},
			error: function(response) {
				if (response.status == 401) {
					//token验证不通过
					window.location.href = "login.html";
				}
			}

		});
	}
	var currentPage = 1; // 当前页码，默认为第一页
	var pageSize = 2; // 总页码
	var pageSizeInit = false

	// 初始化页面数据
	refreshData();

	// 点击搜索按钮时执行
	$("#searchInput").on('input', function() {
		refreshData();
		currentPage = 1
	});
	// 点击词本下拉框时执行
	$("#lexicon").on('click', function() {
		refreshData();
		currentPage = 1
	});

	// 刷新数据
	function refreshData() {
		var searchKeyword = $("#searchInput").val(); // 获取搜索关键字
		var lexicon = $("#lexicon").val()
		// 构建请求数据
		var requestData = {
			key: searchKeyword,
			page: currentPage,
			total: 7,
			lexiconID: lexicon
		};
		// 向接口发送请求，获取数据

		$.ajax({
			url: "http://localhost:8080/word/pageList",
			type: "PUT",
			headers: {
				'Content-Type': 'application/json',
				"token": token
			},
			data: JSON.stringify(requestData), // 将请求数据转换为JSON字符串
			success: function(response) {
				// 清空表格内容
				$("#wordDataTable tbody").empty();
				// 根据接口返回的数据生成表格行
				for (var i = 0; i < response.data.length; i++) {
					var pagewordData = response.data[i];
					// console.log(pagewordData)
					var row = "<tr>" +
							"<td>" + pagewordData.word + "</td>" +
							"<td>" + pagewordData.meaning + "</td>" +
							"<td>" + pagewordData.right + "</td>" +
							"<td>" + pagewordData.wrong + "</td>" +
							"<td>" + pagewordData.familiar + "</td>" +
							"<td>" + pagewordData.interval + "</td>" +
							"<td>" + pagewordData.nextTime + "</td>" +
							"<td>" +
							"<button class='btn btn-primary' onclick='editWord(this,\"" + pagewordData.id +
							"\")' data-row-index='" + i + "'>编辑</button>" +
							"<button class='btn btn-danger' style='margin-left: 7px;' onclick='editWord(this,\"" +
							pagewordData.id +
							"\")' data-row-index='" + i + "'>删除</button>" +
							"</td>" +
							"</tr>";
					$("#wordDataTable tbody").append(row);
				}

				updatePagination(pageSize, currentPage)
			},
			error: function(response) {
				if (response.status == 401) {
					//token验证不通过
					window.location.href = "login.html";
				}
			}

		});
	}

	// 更新分页和页码跳转
	function updatePagination(totalPages, currentPage) {
		var pagination = $("#pagination");
		pagination.empty();

		// 添加上一页按钮
		if (currentPage > 1) {
			pagination.append("<button href='#' class='btn btn-info' style='margin-right: 20px;' onclick='goToPage(" + (
					currentPage - 1) + ")'>上一页</button>");
		}

		// 添加页码按钮

		pagination.append(
				"<input id='inputPage' class='current-page form-control text-center' style='width: 50px;' value='" +
				currentPage + "'>");
		$("#inputPage").on('focus', function() {
			prompt("总页码：" + pageSize)
		});
		$("#inputPage").on('input', function() {
			prompt("总页码：" + pageSize)
		});
		$("#inputPage").on('blur', function() {
			if ($(this).val() > 0 && $(this).val() <= pageSize) {
				goToPage($(this).val());
			}
		});



		// 添加下一页按钮
		if (currentPage < totalPages) {
			pagination.append("<button href='#' class='btn btn-info' style='margin-left:15px ;' onclick='goToPage(" + (parseInt(currentPage) + 1) + ")'>下一页</button>");
		}

	}

	// 跳转到指定页码经济法
	function goToPage(page) {
		console.log(page)
		currentPage = page;
		refreshData();
	}
	var editwordId = null;
	// 编辑单词
	function editWord(edit, id) {
		if ($(edit).text() === "编辑") {
			//编辑单词
			editwordId = id;
			var rowIndex = $(edit).data("row-index"); // 获取行索引
			var word = $("#wordDataTable tbody tr:eq(" + rowIndex + ") td:eq(0)").text(); // 获取单词数据
			var meaning = $("#wordDataTable tbody tr:eq(" + rowIndex + ") td:eq(1)").text(); // 获取意思数据
			// ...
			// 将数据填充到编辑表单中
			$("#editForm input[name='editWord']").val(word);
			$("#editForm input[name='editMeaning']").val(meaning);
			$("#editModal").modal("show");
		} else {
			//删除单词
			if (confirm("确定要删除吗？")) {
				$.ajax({
					url: "http://localhost:8080/word/" + id,
					type: "DELETE",
					headers: {
						'Content-Type': 'application/json',
						"token": token
					},
					data: JSON.stringify(), // 将请求数据转换为JSON字符串
					success: function(response) {
						refreshData()
						prompt("删除成功")
					},
					error: function(response) {
						if (response.status == 401) {
							//token验证不通过
							window.location.href = "login.html";
						}
					}


				});
			}
		}

	}
	//悬浮提示框
	function prompt(text) {
		// 显示悬浮提示
		var toast = $("<div class='toast  text-center' role='alert' aria-live='assertive' aria-atomic='true'>\
				                       <div class='toast-body'>" + text + "</div>\
				                   </div>");
		$("#displayBox").append(toast); // 将悬浮提示添加到页面中
		toast.toast("show"); // 显示悬浮提示
		setTimeout(function() {
			toast.toast("hide"); // 一段时间后隐藏悬浮提示
			toast.remove(); // 移除悬浮提示的HTML元素
		}, 3000); // 设置悬浮提示显示的时间
	}
	//关闭编辑表单
	function closeEdit() {
		prompt("关闭窗口")
		// 关闭模态框
		$("#editModal").modal("hide");
		$("#Quick_brushModal").modal("hide");
	}
	//保存数据
	function saveWord() {
		// 获取表单数据
		var modifyword = $("#editWordInput").val();
		var modifymeaning = $("#editMeaningInput").val();
		var requestData = {
			word: modifyword,
			meaning: modifymeaning,
			id: editwordId
		};
		// 执行保存逻辑
		// ...
		$.ajax({
			url: "http://localhost:8080/word/modify",
			type: "PUT",
			headers: {
				'Content-Type': 'application/json',
				"token": token
			},
			data: JSON.stringify(requestData), // 将请求数据转换为JSON字符串
			success: function(response) {
				refreshData()
				prompt("保存成功")
			},
			error: function(response) {
				if (response.status == 401) {
					//token验证不通过
					window.location.href = "login.html";
				}
			}

		});
		// 关闭模态框
		$("#editModal").modal("hide");

	}

	//词本
	let lexicons = null;

	function getLexiconData() {
		$.ajax({
			url: "http://localhost:8080/lexicons",
			type: "GET",
			headers: {
				'Content-Type': 'application/json',
				"token": token
			},
			success: function(response) {
				lexicons = response.data
				$("#lexicon").empty()
				$("#momoryLexicon").empty()
				$("#lexicon").append("<option value=''  selected>请选择词本</option>")
				for (var i = 0; i < lexicons.length; i++) {
					var option = " <option value='" + lexicons[i].id + "'>" + lexicons[i].name + "</option>"
					$("#lexicon").append(option)
					$("#momoryLexicon").append(option)
				}

			},
			error: function(response) {
				if (response.status == 401) {
					//token验证不通过
					window.location.href = "login.html";
				}
			}

		});
	}

	// 以下为单词记忆功能区=================================================

	if (token === null || token === undefined) {
		window.location.href = "login.html";
	} else {
		// 初始化页面组件逻辑
		var selectElement = $("#loginUserImport");
		selectElement.append('<option value="username">' + userData.username + '</option>');
		selectElement.append('<option value="modif">修改个人信息</option>');
		selectElement.append('<option value="logout">退出登录</option>');
		var setweb = $("#setweb");
		setweb.append('<i id="suo" class="fas fa-chevron-left fa-lg toggle-icon"></i>');
		setweb.append('<i id="bars" class="fas fa-bars fa-2x toggle-icon2"></i>');
		$(".toggle-icon2").toggle();
		var setwebTT = false
		setweb.click(function() {
			if (setwebTT == false) {
				$(".toggle-icon").toggle();
				setwebTT = true
				$(".toggle-icon2").toggle();
				$("#leftnav").css("width", "5%");
				$("#displayBox").css("margin-left", "7.5%");
				$(".leftli").find("p").hide();
			} else {
				$(".toggle-icon2").toggle();
				setwebTT = false
				$(".toggle-icon").toggle();
				$("#leftnav").css("width", "17%");
				$("#displayBox").css("margin-left", "1px");
				$(".leftli").find("p").show();
			}

		});
	}
	//用户信息点击事件
	$("#loginUserImport").change(function() {
		var selectedOption = $(this).val();
		if (selectedOption == "logout") {
			window.location.href = "login.html";
		}
	});

	// 点击"朗读"按钮时朗读单词
	$("#ttsBaiduPlay").on('click', function() {
		word_Voice(word[i].word);
	});

	// 点击"查看"按钮时弹出当前单词
	$("#select").click(function() {
		prompt(word[i].word)
	});

	let quickword = null;
	let iquickword = 0;
	//单词速刷点击事件
	$("#Quick_brush").click(function() {
		getquickData()
		$("#Quick_brushModal").modal("show");
		prompt("单词速刷");
	});

	//单词速刷数据获取
	function getquickData() {
		iquickword = 0
		$.ajax({
			url: "http://localhost:8080/word/quickChoose",
			type: "POST",
			headers: {
				'Content-Type': 'application/json',
				"token": token
			},
			success: function(response) {
				quickword = response.data;
				quickword.forEach(function(item) {
					item.wrong = mergeWordAndWrong(item.meaning, item.wrong);
				});

				setQuickword()
			},
			error: function(response) {
				if (response.status == 401) {
					//token验证不通过
					window.location.href = "login.html";
				}
			}

		});
	}
	//单词遗忘事件
	$('#quick_wordDIV input').on('click',function(){
		$.ajax({
			url: "http://localhost:8080/word/quickUpdate",
			type: "PUT",
			headers: {
				'Content-Type': 'application/json',
				"token": token
			},
			data: JSON.stringify({
				id: quickword[iquickword].id,
				action: 'false'
			}), // 将请求数据转换为JSON字符串
			success: function(response) {

			},
			error: function(response) {
				if (response.status == 401) {
					//token验证不通过
					window.location.href = "login.html";
				}
			}
		});
		setloginfo('false', quickword[iquickword].word, quickword[iquickword].meaning, "∞", "∞")
		iquickword++
		setQuickword()
	})
	//单词速刷选项点击事件
	$('#quick_chooseDIV input').on('click', function() {
		let quickAction = 'false'
		if ($(this).val() == quickword[iquickword].meaning) {
			$(this).css("background-color", "green")
			quickAction = 'right'
		} else {
			$(this).css("background-color", "red")
			//单词错误
			prompt(quickword[iquickword].meaning)
		}
		if (quickword.length - 1 <= iquickword) {
			learnOK()
			prompt("学习完成")
			if (confirm("已完成学习，是否继续拉取数据？")) {
				getquickData()
			}
		} else {
			console.log(JSON.stringify({
				id: quickword[iquickword].id,
				action: quickAction
			}))
			$.ajax({
				url: "http://localhost:8080/word/quickUpdate",
				type: "PUT",
				headers: {
					'Content-Type': 'application/json',
					"token": token
				},
				data: JSON.stringify({
					id: quickword[iquickword].id,
					action: quickAction
				}), // 将请求数据转换为JSON字符串
				success: function(response) {

				},
				error: function(response) {
					if (response.status == 401) {
						//token验证不通过
						window.location.href = "login.html";
					}
				}
			});
			setloginfo(quickAction, quickword[iquickword].word, quickword[iquickword].meaning, "∞", "∞")
			iquickword++
			setQuickword()
		}
	});
	//设置速刷单词的选项内容
	function setQuickword() {
		word_Voice(quickword[iquickword].word)
		$("#quick_wordDIV_text").text(quickword[iquickword].word);
		var inputs = $('#quick_chooseDIV input');
		setTimeout(function() {
			inputs.css("background-color", "dodgerblue")
		}, 500);
		$(inputs[0]).val(quickword[iquickword].wrong[0])
		$(inputs[1]).val(quickword[iquickword].wrong[1])
		$(inputs[2]).val(quickword[iquickword].wrong[2])
		$(inputs[3]).val(quickword[iquickword].wrong[3])

		// inputs.css("background-color","dodgerblue")
	}

	// 合成数据
	function mergeWordAndWrong(word, wrong) {
		let combinedArray = wrong.concat(word);
		let mergedArray = [];
		while (mergedArray.length < 4 && combinedArray.length > 0) {
			let randomIndex = Math.floor(Math.random() * combinedArray.length);
			let randomItem = combinedArray.splice(randomIndex, 1)[0];
			mergedArray.push(randomItem);
		}

		return mergedArray;
	}





	//初始化页面数据
	function init() {
		// 根据输入的单词判断是否正确，并进行相应处理
		$("body").delegate("textarea", "input", function() {
			if (word[i].word == $("#ttsBaiduText").val()) {
				word_Voice($("#ttsBaiduText").val());
				updateWord('right', word[i].word, $("#ChineseText").val());
				setWord(i++);
			} else if (word[i].word.includes($("#ttsBaiduText").val())) {
				document.getElementById("ttsBaiduText").style.color = "green";
			} else {
				document.getElementById("ttsBaiduText").style.color = "red";
			}

		});
		$("#addWordTOdb").hide()
		$("#momoryLexicon").hide();
		$("#lexiconDIV").hide();
		// 初始化页面时获取新的单词数据
		getWordData();
	}

	var word = [];

	// 获取单词数据函数
	function getWordData() {
		fetch('http://localhost:8080/word', {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				"token": token
			},
			body: JSON.stringify({

			})
		}).then(response => {
			if (!response.ok) {
				if (response.status == 401) {
					//token验证不通过
					window.location.href = "login.html";
				}
				throw new Error('请求失败');
			}
			return response.json();
		}).then(data => {
			// 请求成功处理返回的数据
			word = data.data;
			i = 0;
			setWord()
		}).catch(error => {
			// 请求失败处理错误信息
			console.error(error);
		});

	}

	//初始化数据
	init()
	// 点击"汉译英"按钮时切换到汉译英模式
	$("#ChineseToEnglish").on('click', function() {
		//初始化单词数据和组件功能
		init()
		i = 0;
		$("#addWordTOdb").hide();
		$("#momoryLexicon").hide();
		$("#forget").show();
		$("#select").show();
		$("#ttsBaiduPlay").show();
		setWord();
	});


	// 点击"遗忘"按钮时更新当前单词为错误答案，并显示下一个单词
	$("#forget").click(function() {
		prompt(word[i].word)
		updateWord('wrong', word[i].word, $("#ChineseText").val());
		setWord(i++);
	});

	// 设置当前单词和翻译到文本框中
	function setWord() {
		if (word.length == 0) {
			$("#ttsBaiduText").val("You will succeed!");
			$("#ChineseText").val("你会成功！");
			learnOK()
			$("#addWordTOdb").show();
			$("#forget").hide();
		} else {
			if (i < word.length) {
				if (word[i].familiar < 0.7)
					word_Voice(word[i].word)
				$("#ttsBaiduText").val("");
				$("#ChineseText").val(word[i].meaning);
			} else {
				getWordData()
			}
		}
	}

	// 点击"添加单词"按钮时切换到添加单词模式
	$("#addWord").on('click', function() {
		$("#ttsBaiduPlay").hide();
		$("#select").hide();
		$("#addWordTOdb").show();
		$("#momoryLexicon").show();
		$("#addWordTOdb").text("添加到数据库");
		$("#forget").hide();
		getLexiconData()
		$("body").undelegate("textarea", "input"); // 取消之前绑定的input事件

		$("#ttsBaiduText").val("");
		$("#ChineseText").val("");
	});

	// 点击"添加到数据库"按钮时将单词数据添加到数据库
	$("#addWordTOdb").click(function() {
		if ($("#ttsBaiduText").val() !== "" && $("#ChineseText").val() !== "") {
			fetch('http://localhost:8080/word/insert', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
					"token": token
				},
				body: JSON.stringify({
					word: $("#ttsBaiduText").val(),
					meaning: $("#ChineseText").val(),
					lexiconID: $("#momoryLexicon").val()
				})
			}).then(response => {
				if (!response.ok) {
					if (response.status == 401) {
						//token验证不通过
						window.location.href = "login.html";
					}
					throw new Error('请求失败');
				}
				return response.json();
			}).then(data => {
				// 请求成功处理返回的数据
				prompt(data.msg)
			}).catch(error => {
				// 请求失败处理错误信息
				console.error(error);
			});
			$("#ttsBaiduText").val("");
			$("#ChineseText").val("");
		} else {
			alert("请输入有效内容");
		}
	});



	//日志
	function setloginfo(action, words, meaning, rightnumber, wrongnumber) {
		var trcolor = null
		//设置日志
		if (action === "right") {
			trcolor = "green"
		} else
			trcolor = "red"
		var newRow = '<tr class="text-center" style="color:' + trcolor + ';">' +
				'<td>' + words + '</td>' +
				'<td>' + meaning + '</td>' +
				'<td>' + rightnumber + '</td>' +
				'<td>' + wrongnumber + '</td>' +
				'</tr>';
		$('#logInfoTable').append(newRow);
		if (action === "right") {
			$(newRow).css("color", "green")
		} else {
			$(newRow).css("color", "red")
		}
	}

	function learnOK(){
		fetch('http://localhost:8080/user', {
			method: 'PUT',
			headers: {
				'Content-Type': 'application/json',
				"token": token
			},
			body: JSON.stringify({})
		}).then(response => {
			if (!response.ok) {
				if (response.status === 401) {
					//token验证不通过
					window.location.href = "login.html";
				}
				throw new Error('请求失败');
			}
			return response.json();
		}).then(data => {
			// 请求成功处理返回的数据
			if (data.code === 200)
				prompt(data.msg)
		}).catch(error => {
			// 请求失败处理错误信息
			console.error(error);
		});
	}

	// 更新单词数据函数
	function updateWord(action, words, meaning) {
		$("#nextEnglish").text(word[i].word)
		$("#nextChinese").text(word[i].meaning)
		console.log(word[i])
		//设置日志
		setloginfo(action, words, meaning, word[i].right, word[i].wrong)
		document.getElementById('wordLoginfo').scrollIntoView();

		fetch('http://localhost:8080/word', {
			method: 'PUT',
			headers: {
				'Content-Type': 'application/json',
				"token": token
			},
			body: JSON.stringify({
				action: action,
				word: words,
				meaning: meaning,
				lexiconID: ""
			})
		}).then(response => {
			if (!response.ok) {
				if (response.status == 401) {
					//token验证不通过
					window.location.href = "login.html";
				}
				throw new Error('请求失败');
			}
			return response.json();
		}).then(data => {
			// 请求成功处理返回的数据
			if (data.code === 200)
				alert("添加成功")
			else if (data.code === 0)
				alert(data.msg)
		}).catch(error => {
			// 请求失败处理错误信息
			console.error(error);
		});
	}

	// 朗读单词函数
	function word_Voice(word) {
		var utterThis = new SpeechSynthesisUtterance();
		utterThis.text = word;
		utterThis.volume = 1;
		utterThis.rate = 0.7;
		speechSynthesis.speak(utterThis);
	}
</script>
</body>
</html>